package org.hekang.config;

import lombok.AllArgsConstructor;
import org.hekang.properties.HyperLedgerFabricProperties;
import org.hyperledger.fabric.gateway.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

/**
 * 描述: 网络配置
 *
 * @author hekang
 * @date 2024-04-19 15:54
 */
@Configuration
@AllArgsConstructor
public class HyperLedgerFabricConfig {
    HyperLedgerFabricProperties hyperLedgerFabricProperties;

    /**
     * 描述: 获取网关
     *
     * @returns org.hyperledger.fabric.gateway.Gateway
     * @author hekang
     * @date 2024/4/19 16:05
     */
    @Bean
    public Gateway gateway() throws Exception {
        // 读取配置org1证书
        BufferedReader certificateReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getCertificatePath()), StandardCharsets.UTF_8);

        // 读取org1 X509私钥
        X509Certificate certificate = Identities.readX509Certificate(certificateReader);

        // 读取配置org1私钥
        BufferedReader privateKeyReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getPrivateKeyPath()), StandardCharsets.UTF_8);

        // 读取org1私钥
        PrivateKey privateKey = Identities.readPrivateKey(privateKeyReader);

        // 创建钱包
        Wallet wallet = Wallets.newInMemoryWallet();
        // 创建添加用户
        wallet.put("user1", Identities.newX509Identity(hyperLedgerFabricProperties.getMspId(), certificate, privateKey));
        // 用户创建网关
        Gateway.Builder builder = Gateway.createBuilder()
                .identity(wallet, "user1")
                .networkConfig(Paths.get(hyperLedgerFabricProperties.getNetworkConnectionConfigPath()));

        Gateway gateway = builder.connect();

        System.out.println("======创建网关========》 " + gateway + "-机构：" + hyperLedgerFabricProperties.getMspId());

        return gateway;
    }

    /**
     * 描述: 获取demo1合约实例
     *
     * @return
     * @throws Exception
     */
    @Bean
    public Contract contractDemo() throws Exception {
        // 返回合约实例
        return getDefaultNetwork().getContract("hyperledger-fabric-contract-demo", "CatContract");
    }

    /**
     * 描述: 获取网络通道实例
     *
     * @returns org.hyperledger.fabric.gateway.Network
     * @author hekang
     * @date 2024/4/19 17:19
     */
    @Bean
    public Network getDefaultNetwork() throws Exception {
        // 获取网关
        Gateway gateway = gateway();
        // 返回网络通道实例
        return gateway.getNetwork("mychannel");
    }
}
